package com.huibei.wateradmin.authority.common;

import com.huibei.wateradmin.authority.domain.User;
import com.huibei.wateradmin.authority.service.AccountService;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

/**
 * Created by wanglinlin on 2016/7/18.
 */
@Component
public class AppInterceptor implements HandlerInterceptor {
    @Autowired
    private AccountService accountService;
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        System.out.println("请求处理前  拦截器起作用了。。。。");
        Enumeration<String> list =httpServletRequest.getParameterNames();
        while (list.hasMoreElements()){
            String name = list.nextElement();
            System.out.println("============="+ name + ":" + httpServletRequest.getParameter(name));
        }
        Object userInfo = httpServletRequest.getSession().getAttribute("userInfo");
        String uri = httpServletRequest.getRequestURI();
        String servletPath = httpServletRequest.getServletPath();
        System.out.println(uri);
        System.out.println(httpServletRequest.getContextPath());
        System.out.println(httpServletRequest.getServletPath());
        if (userInfo == null) {
            if (uri.indexOf("toLogin") >= 0 || uri.indexOf("login") >= 0 || uri.indexOf("register") >= 0) {

                return true;
            } else {
                httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/admin/account/toLogin");
                return false;
            }
        } else {
            BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(httpServletRequest.getServletContext());
            accountService = (AccountService)factory.getBean("accountService");
            User user = (User)userInfo;
            return accountService.checkAuthority(user , servletPath);
        }

    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

        //System.out.println("请求处理之后进行调用，但是在视图被渲染之前，拦截器起作用了。。。。");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        //System.out.println("请求结束之后，拦截器起作用了。。。。");
    }
}
